function [ptr] = find_data(filename, searchrec, databasename)
% This function tries to find the data in the current control database
% that corresponds to the file with filename (qualified with an extension) and the first record firstrec
% ptr is either null on return (data not found)
% or points to the CONTROL(ptr) that holds the requested data.
% if more than one entry is found, ptr will be an array for each entry
% (you figure it out)
% 12 jan 2000 P. Manis
% Note that if firstrec is in the middle of the sequence, we will also report the entry
% %
% example:
% find_data('13feb02b.mat', 6, 'RES-SCPCR') should return a valid value...
% Modified 9/15/02 to load the correct data base if the file is not in this one.
%
ptr=[];
if(nargin > 2) % we need to use the databasename to verify the database...
   db = datac('getdatabase'); % get the currently open data base
   [p f e] = fileparts(db); % just reduce to the name - path is not relevant
   if(~strcmp(databasename, f))
      err = datac('loadmatctl', databasename);
      if(err ~= 0)
         QueMessage('find_data: unable to open data base: %s', 1);
         return;
      end; % otherwise, we did load it
   end;   % or it was already in memory
end;

c=datac('control'); % call getuserdata in the right format
fnlist=[{c.filename}']; % extract the filenames
fnmatch=strmatch(filename, fnlist, 'EXACT');
if(isempty(fnmatch))
   disp(sprintf('File %s not found in data base', filename))
   return;
end;
for i = 1:length(fnmatch)
   if(ischar(c(fnmatch(i)).recbeg))
      c(fnmatch(i)).recbeg = str2num(c(fnmatch(i)).recbeg);
   end;
   if(ischar(c(fnmatch(i)).recend))
      c(fnmatch(i)).recend = str2num(c(fnmatch(i)).recend);
   end;
end;

f1=[c(fnmatch).recbeg]; % this is the list of first records in the matched name
f2=[c(fnmatch).recend];
p=find(f1 <= searchrec & f2 >= searchrec);
if(isempty(p))
   disp(sprintf('File %s does not have record %d in data base', filename, searchrec))
end;
ptr=fnmatch(p);
return;

